// import mqtt from "mqtt";
import mqtt from "mqtt/dist/mqtt";
import { getAuthHeaderInfo } from "/@/api/req";
import authCache from "./cache/authCache";

const host = "192.1.5.252";
const port = "31883";
// const host = "broker.emqx.io";
// const port = "8083";
export function createConnection() {
  const info = authCache.getUserInfo();
  const headerInfo = getAuthHeaderInfo();
  if (!info || !headerInfo) return;
  const connectUrl = `ws://${host}:${port}/mqtt`;
  let client: any = null;
  try {
    client = mqtt.connect(connectUrl, {
      host,
      port,
      clean: true, // 保留会话
      connectTimeout: 4000, // 超时时间
      reconnectPeriod: 4000, // 重连时间间隔
      // 认证信息
      clientId: info.userId + "PC",
      username: info.userId + "|PC",
      password: headerInfo.token,
      // clientId: "mqttjs_3be2c321",
      // username: "emqx_test",
      // password: "emqx_test",
    });
  } catch (error) {
    console.log("mqtt.connect error", error);
  }
  if (!client) return;
  client.on("connect", () => {
    console.log("Connection succeeded!");
  });
  client.on("error", (error) => {
    console.log("Connection failed", error);
  });
  client.on("message", (topic, message) => {
    console.log(`Received message ${message} from topic ${topic}`);
  });
}
